<template>
	<div>
		<el-row class="tac">
			<el-col :span="4">
				<div class="setheight_scroller">
					<el-card class="box-card" style="height: 800px;">
						<div>
							<h4>权限名称</h4>
							<el-button type="text" @click="AddPowerTree">添加权限</el-button>
							<el-button type="text" @click="DelPowerTree">删除权限</el-button>
						</div>
						<br />
						<el-tree class="filter-tree " :data="PowerTreeData" :props="defaultProps" node-key="id" :expand-on-click-node="false" @current-change="handleClick" default-expand-all ref="tree">
						</el-tree>
					</el-card>
				</div>
			</el-col>

			<el-col :span="20">
				<el-row>
					<el-col :span="8">
						<el-input placeholder="请输入权限ID或名称" v-model="p_power_id">
							<template slot="prepend">权限:</template>
						</el-input>
					</el-col>
					<el-col :span="16">
						<el-button type="primary" @click="showdata">查询</el-button>
						<el-button type="primary" @click="showAdd">增加</el-button>
						<el-button type="primary" @click="showDel">删除</el-button>
						<el-button type="primary" @click="showAllocation">分配</el-button>
						<el-button type="primary" @click="showExport">导出</el-button>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span='16'>
						<el-card class="box-card" style="height: 800px;">
							<div class="setheight_scroller">
								<el-row>
									<div style="font-weight:bold;font-size: 20px;">{{treemsg}} </div>
								</el-row>
								<el-table :data="powerData.slice((currentPage-1)*pagesize,currentPage*pagesize)" showOverflowTooltip  stripe border tooltip-effect="dark"  @selection-change="handleSelectionChange" @row-click="rowClick" ref="multipleTable">
									<el-table-column type="selection" width="50"> </el-table-column>
									<el-table-column width='150' prop="power_id" label="权限ID" show-overflow-tooltip></el-table-column>
									<el-table-column width='150' prop="power_name" label="权限名称" show-overflow-tooltip></el-table-column>
									<el-table-column label="内容" width='205' prop="content" show-overflow-tooltip>
										<template slot-scope="scope">
											<a href="javascript:;" @click="show_article(scope.$index, scope.row)" class="buttonText">{{scope.row.content}}</a>
										</template>
									</el-table-column>

									<el-table-column prop="remarks" label="描述" width="70"></el-table-column>
									<el-table-column label="操作" width="150">
										<template slot-scope="scope">
											<!--/knowledge/knowledgeAdd-->
											<i class="el-icon-edit" @click="showEdit(scope.$index, scope.row)">   修改</i>
											<router-link :to="{path: '/knowledge/knowledgeAdd', query: {power_key:scope.row.power_key}}">
												<i class="el-icon-edit"> 内容链接  </i>
											</router-link>
										</template>
									</el-table-column>

								</el-table>
								<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="powerData.length">
								</el-pagination>
							</div>
						</el-card>
					</el-col>

					<el-col :span='8'>
						<el-card class="box-card" style="height: 800px;">
							<el-row>
								<div style="font-weight:bold;font-size: 20px;">{{powermsg}} </div>
							</el-row>

							<el-table :data="roleData" showOverflowTooltip style="width: 100%" stripe border tooltip-effect="dark" height="500">
								<el-table-column prop="role_name" label="角色名称" show-overflow-tooltip></el-table-column>
								<el-table-column label="操作" width="100">
									<template slot-scope="scope">
										<el-button size="small" type="primary" @click="delRole(scope.$index,scope.row)">删除</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-card>
					</el-col>
				</el-row>
			</el-col>
		</el-row>

		<!--新增界面-->
		<el-dialog :title="text" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="resetForm('addForm')" style="padding-bottom:0;">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm" style="height:240px;">
				<el-form-item label="权限ID" prop="power_id">
					<el-input v-model="addForm.power_id" auto-complete="off" placeholder="请输入权限ID"></el-input>
				</el-form-item>
				<el-form-item label="权限名称" prop="power_name">
					<el-input v-model="addForm.power_name" auto-complete="off" placeholder="请输入权限名称"></el-input>
				</el-form-item>
				<el-form-item label="分类" prop="classify">
					<el-select v-model="addForm.classify" placeholder="请选择" filterable style='width:100%'>
						<el-option v-for="item in dictData" :key="item.dict_id" :label='item.detail_name' :value="item.dict_id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="描述" prop="remarks">
					<el-input type="textarea" placeholder="请输入描述" auto-complete="off" :rows="4" v-model="addForm.remarks"></el-input>
				</el-form-item>
			</el-form>
			<br />
			<div slot="footer" class="dialog-footer" style="text-align: left; margin-left:30px;margin-left:80px;">
				<el-button type="primary" @click.native="addSubmit">提交</el-button>
				<el-button @click="reset()">重置</el-button>
			</div>
		</el-dialog>

		<!--新增权限   @close="resetForm('addForm')"-->
		<el-dialog :title="text" :visible.sync="PowerTreeVisible" :close-on-click-modal="false" style="padding-bottom:0;">
			<el-form :model="addPowerTreeForm" label-width="80px" :rules="addPowerTreeRules" ref="addPowerTreeForm" style="height:240px;">
				<el-form-item label="权限名称" prop="tree_name">
					<el-input v-model="addPowerTreeForm.tree_name" auto-complete="off" placeholder="请输入权限名称"></el-input>
				</el-form-item>
				<el-form-item label="上级权限">
					<el-cascader placeholder="" :options="PowerTreeData" filterable change-on-select :props="defaultCascader" clearable v-model='selectFatherKey'></el-cascader>
				</el-form-item>
				<el-form-item label="显示顺序" prop="displayindex">
					<el-input v-model="addPowerTreeForm.displayindex" auto-complete="off" placeholder="请输入显示顺序"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer" style="text-align: left; margin-left:30px;margin-left:80px;">
				<el-button type="primary" @click.native="addPowerTreeSubmit">提交</el-button>
				<el-button @click="resetFormregion()">重置</el-button>
			</div>
		</el-dialog>

		<!--分配权限管理-->
		<el-dialog title="分配角色权限" :visible.sync="addUserVisible" width="30%" @close="handleClose">
			<span>选择角色</span>
			<el-select v-model="checkedRole" filterable multiple placeholder="请选择">
				<el-option v-for="item in noRoleUserData" :key="item.role_key" :label="item.role_name" :value="item.role_key">
				</el-option>
			</el-select>
			<span slot="footer" class="dialog-footer">
			    <el-button @click="addUserVisible = false;">取 消</el-button>
			    <el-button type="primary" @click="addRole">确 定</el-button>
			  </span>
		</el-dialog>

		<el-dialog title="文章详情" :visible.sync="showVisible">

			<mavon-editor v-model="testValue" style="height: 100%" ref="md" :toolbarsFlag="false" :subfield="false" defaultOpen="preview"></mavon-editor>
			<br />

			<span slot="footer" class="dialog-footer">
			    <el-button @click="showVisible = false;">关闭</el-button>
			 </span>
		</el-dialog>

	</div>
</template>

<script>
	
//	import co from 'co';
//	import axios from 'axios';
	import { query, apiparas, execute } from '../../api/api';
	import { Cookie, Client } from '../../js/common';
	export default {
		data() {
			return {
				noRoleUserData: [],
				roleData: [],
				checkedRole: [],
				PowerTreeData: [],
				selectFatherKey: [],
				multipleTablePower1: [],
				currentPage: 1,
				pagesize: 10,
				powerData: [],
				treemsg: '',
				dictData: [],
				p_power_id: '',
				text: '',
				multipleTablePower: [],
				editId: '',
				powerid: '',
				power_key: '',
				selectRow: {},
				multipleTable: [],
				testValue: '',
				powerpid: '',
				powermsg: '',
				addUserVisible: false,
				addFormVisible: false,
				showVisible: false,
				defaultCascader: {
					value: 'id',
					children: 'subs',
					label: 'tree_name'
				},
				defaultProps: {
					id: 'id',children: 'subs',label: 'tree_name'
				},
				addPowerTreeForm: {
					tree_name: '',
					displayindex: '',
				},
				addForm: {
					power_id: '',
					power_name: '',
					classify: '',
					remarks: ''
				},
				row_tree_name:"",
				PowerTreeVisible: false,
				showknowledge: {}, //选择浏览得知识对象
				isAddShow: false,
				isEditShow: false,
				editFormVisible: false,
				powerto: '',
				addPowerTreeRules: {
					tree_name: [{
						required: true,message: '请输入权限名称',trigger: 'blur'
					}, ],
					displayindex: [{
						required: true,message: '请输入显示顺序',trigger: 'blur'
					}, ]
				},
				addFormRules: {
					power_id: [{
						required: true,message: '请输入权限ID',trigger: 'blur'
					}, ],
					power_name: [{
						required: true,message: '请输入权限名称',trigger: 'blur'
					}, ],
					classify: [{
						required: true,message: '请输入分类',trigger: 'blur'
					}, ]
				},
			}
		},
		components: {
			//注册组件
		},
		watch: {
			multipleTable: function() {

			}
		},
		mounted: function() {
			//生命周期
		},
		computed: {
			//计算属性
		},
		methods: { //函数
			
			handleClose() {
				this.checkedRole = [];
			},
			rowClick(row, event, column) {
				this.powermsg = row.power_name
				this.power_key = row.power_key;
				this.getRolePower();
				this.toggleSelection(row);
			},
			handleSelectionChange(val) {
				this.multipleTable = val;
				this.multipleTablePower = this.multipleTable;
			},
			toggleSelection(rows) {
				if(this.multipleTable.length > 0) {
					this.$refs.multipleTable.clearSelection();
				}
				this.$refs.multipleTable.toggleRowSelection(rows);
			},
			resetFormregion() {
				this.addPowerTreeForm.tree_name = '',
					this.addPowerTreeForm.displayindex = ''
			},
			reset: function() { //重置
				if(this.isEditShow) {
					this.addForm.power_id = this.selectRow.power_id;
					this.addForm.power_name = this.selectRow.power_name;
					this.addForm.classify = this.selectRow.classify;
					this.addForm.remarks = this.selectRow.remarks;
				} else {
					this.addForm = {
						power_id: '',
						power_name: '',
						classify: '',
						remarks: ''
					};
				}
			},
			resetForm: function(formName) { //重置
				this.$refs[formName].resetFields();
			},

			//分配权限角色
			showAllocation() {
				this.multipleTablePower1 = this.multipleTablePower
				this.addUserVisible = true;
				this.getNoRoleUserData();
			},

			delRole(index, row) {
				var jsonparas = [];
				apiparas.pushPara(jsonparas, 'power_key', this.power_key);
				apiparas.pushPara(jsonparas, 'role_key', row.role_key);
				let _paras = apiparas.getParas('default', 'basic|del_power_role', jsonparas);
				execute(_paras).then(response => {
					if(response.errid == 0) {
						this.getRolePower();
						this.$message({
							message: '恭喜你，成功删除一条数据',
							type: 'success'
						});
					} else {
						this.$notify.error({
							title: '删除失败',
							message: response.errmsg
						});
					}
				});
			},
			//获取权限角色用户
			getRolePower() {
				var jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'power_key', this.power_key);
				//this.$notify({title: '信息提示',message: '正在加载数据，请稍后！',type: 'info'});
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_power_role', jsonparas);
				query(_paras).then(response => {
					var json_data = response.result;
					this.roleData = json_data;
				});
			},

			getNoRoleUserData: function() {
				var jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'role_name', '');
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_role', jsonparas);
				query(_paras).then(response => {
					this.noRoleUserData = response.result;
				});
			},

			//增加权限节点树
			AddPowerTree() {
				this.PowerTreeVisible = true;
				this.text = '新增';
				this.selectFatherKey = [];
				this.addPowerTreeForm = {
					tree_name: '',
					displayindex: '',
				}
			},
			//删除权限节点树
			DelPowerTree() {
				this.$confirm('是否确定删除'+this.row_tree_name+'权限?', '提示', {
					confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'
				}).then(() => {
				var jsonparas = [];
				apiparas.pushPara(jsonparas, 'power_tree_key', this.powerid);
				let _paras = apiparas.getParas('default', 'basic|del_power_tree', jsonparas);
				execute(_paras).then(response => {
					if(response.errid == 0) {
						this.showPowerTreeData();
						this.addFormVisible = false;
						this.showdata();
						this.$message({
							showClose: true,
							message: '成功删除',
							type: 'success'
						});
					} else {
						this.$message({
							showClose: true,
							message: '删除失败',
							type: response.errmsg
						});
					}
				});
				}).catch(() => {
					this.$message({
						type: 'info',message: '已取消删除'
					});
				});
			},

			showdata: function() { //查询数据
				//显示数据
				var jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'power_tree_key', this.powerid);
				apiparas.pushPara(jsonparas, 'power_id', this.p_power_id);
				apiparas.pushPara(jsonparas, 'classify', '');
				//this.$notify({title: '信息提示',message: '正在加载数据，请稍后！',type: 'info'});
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_power', jsonparas);
				query(_paras).then(response => {
					var json_data = response.result;
					this.powerData = json_data;
					
				});
			},
			//点击权限树节点时候触发的事件
			handleClick(row) {
				this.row_tree_name=row.tree_name;
				this.treemsg = row.tree_name;
				this.powerpid = row.pid;
				this.powerid = row.id;
				this.showdata();
			},

			//获取权限树节点数据
			showPowerTreeData() {
				//显示数据
				let jsonparas = [];
				let paras = apiparas.getParas_rtype('default', 'basic|get_power_tree', 3, jsonparas);
				query(paras).then(response => {
					var json_data = response.result;
					this.PowerTreeData = json_data;
				});
			},

			//增加角色
			addRole() {
				var keys = '';
				for(var i = 0; i < this.multipleTablePower1.length; i++) {
					keys += this.multipleTablePower1[i]['power_key'] + ",";
				}
				keys = keys.substring(0, keys.length - 1);
				if(keys == '') {
					this.$notify({
						title: '信息提示',
						message: '请选择要为那个权限添加角色！',
						type: 'info'
					});
					return;
				}

				let str = '';
				for(let i = 0; i < this.checkedRole.length; i++) {
					str += this.checkedRole[i] + ','
				}
				str = str.substring(0, str.length - 1);
				var jsonparas = [];
				apiparas.pushPara(jsonparas, 'power', keys);
				apiparas.pushPara(jsonparas, 'role', str);
				let _paras = apiparas.getParas('default', 'basic|insert_power_role', jsonparas);
				execute(_paras).then(response => {
					this.addUserVisible = false;
					this.getRolePower();
					this.checkedUser = [];
					if(response.errid == 0) {
						this.$message({
							showClose: true,
							message: '成功添加',
							type: 'success'
						});
					} else {

						this.$message({
							showClose: true,
							message: '添加失败',
							type: response.errmsg
						});
					}
				});
			},

			getDict: function() {
				let jsonparas = [];
				//增加查询条件
				//查询汇总
				let _paras = apiparas.getParas('default', 'sys|get_powerOfdict', jsonparas);
				query(_paras).then(response => {
					this.dictData = response.result;
				});
			},
			//新增
			showAdd: function() { //显示新增对话框
				this.addFormVisible = true;
				this.text = '新增';
				this.isEditShow = false;
				this.addForm = {
					power_id: '',
					power_name: '',
					classify: '',
					remarks: ''
				};
				this.getDict();
			},

			//编辑
			showEdit: function(index, row) {
				this.addFormVisible = true;
				this.text = '编辑';
				this.selectRow = row;
				this.addForm.power_id = row.power_id;
				this.addForm.power_name = row.power_name;
				this.addForm.classify = row.classify;
				this.addForm.remarks = row.remarks;
				this.editId = row.power_key;
				this.getDict();
				this.isEditShow = true;
			},

			//增加权限树节点
			addPowerTreeSubmit() {
				let fatherKey = this.selectFatherKey.pop();
				
				if(fatherKey === undefined) {
					fatherKey = 0;
				}
				//增加条件
				let jsonparas = [
				{'name': 'father_key','value': fatherKey},
				{'name': 'tree_name','value': this.addPowerTreeForm.tree_name},
				{'name': 'displayindex','value': this.addPowerTreeForm.displayindex}
				];
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|insert_power_tree', jsonparas);
				execute(_paras).then(response => {
					if(response.errid == 0) {
						this.PowerTreeVisible = false;
						this.showPowerTreeData();
						this.$message({
							showClose: true,message: '添加成功',type: 'success'
						});
					} else {
						this.$message({
							showClose: true,message: response.errmsg,type: 'error'
						});
					}
				});
			},

			addSubmit: function() { //提交
				if(this.isEditShow) {
					var jsonparas = [];
					//增加查询条件  
					let jsonparas = [
					{'name': 'power_key','value': this.editId},
					{'name': 'power_id','value': this.addForm.power_id},
					{'name': 'power_name','value': this.addForm.power_name},
					{'name': 'classify','value': this.addForm.classify},
					{'name': 'remarks','value': this.addForm.remarks}
					]
					//查询汇总
					let _paras = apiparas.getParas('default', 'basic|update_power', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0) {
							this.addFormVisible = false;
							this.$message({
								showClose: true,message: '修改成功',type: 'success'
							});
							this.showdata();
						} else {
							this.$message({
								showClose: true,message: response.errmsg,type: 'error'
							});
						}
					});
				} else {
					//处理添加
					var jsonparas = [];
					//增加查询条件
					let jsonparas = [
					{'name': 'power_id','value': this.addForm.power_id},
					{'name': 'power_tree_key','value': this.powerid},
					{'name': 'power_name','value': this.addForm.power_name},
					{'name': 'classify','value': this.addForm.classify},
					{'name': 'remarks','value': this.addForm.remarks}
					]
					//查询汇总
					let _paras = apiparas.getParas('default', 'basic|insert_power', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0) {
							this.addFormVisible = false;
							this.$message({
								showClose: true,message: '成功添加',type: 'success'
							});
							this.showdata();
						} else {
							this.$message({
								showClose: true,message: response.errmsg,type: 'error'
							});
						}
					});
				}
			},
			//删除
			showDel: function() {
				var keys = '';
				for(var i = 0; i < this.multipleTablePower.length; i++) {
					keys += this.multipleTablePower[i].power_key + ",";
				}
				if(keys == '') {
					this.$notify({
						title: '信息提示',message: '请选择要删除的明细！',type: 'info'
					});
					return;
				}
				keys = keys.substring(0, keys.length - 1);
				this.$confirm('此操作将永久删除选中的权限, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let jsonparas = [];
					apiparas.pushPara(jsonparas, 'keys', keys);
					let _paras = apiparas.getParas('default', 'basic|del_power', jsonparas);
					execute(_paras).then(response => {
						let json_data = response.result;
						if(response.errid == 0) {
							this.$message({
								showClose: true,message: '成功删除ID为' + keys + '的数据',type: 'success'
							});
							this.showdata();
						} else {
							this.$message({
								showClose: true,message: '删除失败',type: 'error'
							});
						}
					});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			showExport: function() //导出
			{
				this.downloadLoading = true
				require.ensure([], () => {
					const {
						export_json_to_excel
					} = require('@../../vendor/Export2Excel')
					const tHeader = ['权限ID', '权限名称', '描述', '分类', '创建时间', '修改时间'];
					const filterVal = ['power_id', 'power_name', 'remarks', 'classify', 'create_time', 'update_time'];
					const list = this.powerData;
					const _data = this.formatJson(filterVal, list);
					export_json_to_excel(tHeader, _data, '权限管理','权限管理');
				})
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]))
			},
			tableRowClassName(row, rowIndex) {
				return '';
			},
			handleSizeChange: function(size) {
				this.pagesize = size;
			},
			handleCurrentChange: function(currentPage) {
				this.currentPage = currentPage;
			},
			

			show_article: function(index, row) {
				this.showVisible = true;
				this.showknowledge = row;
				let _this = this;
				let fileName = row.content;
				//console.log('fileName:'+fileName);
				
				let client = Client.NewOSS();
				
				async function getBuffer() {
					try {
						let result = await client.get(fileName);
						_this.testValue = result.content.toString()
					} catch(e) {
						console.log(e);
					}
				}
				getBuffer();
			},

		},
		created: function() {
			this.showPowerTreeData();
		}
	}
</script>

<style>
	.setheight_scroller {
		height: 790px;
		overflow: auto;
	}
</style>